import jwt from 'jsonwebtoken';
import config from '../config/index.js';
import { User, Admin } from '../models/index.js';

// 用户认证中间件
export const authenticateUser = async (req, res, next) => {
  try {
    const token = req.header('Authorization')?.replace('Bearer ', '');
    
    if (!token) {
      return res.status(401).json({
        code: 401,
        message: '访问令牌缺失'
      });
    }

    const decoded = jwt.verify(token, config.jwt.secret);
    const user = await User.findByPk(decoded.userId);
    
    if (!user || !user.is_active) {
      return res.status(401).json({
        code: 401,
        message: '用户不存在或已被禁用'
      });
    }

    req.user = user;
    next();
  } catch (error) {
    if (error.name === 'JsonWebTokenError') {
      return res.status(401).json({
        code: 401,
        message: '无效的访问令牌'
      });
    }

    if (error.name === 'TokenExpiredError') {
      return res.status(401).json({
        code: 401,
        message: '访问令牌已过期'
      });
    }

    return res.status(500).json({
      code: 500,
      message: '认证失败'
    });
  }
};

// 管理员认证中间件
export const authenticateAdmin = async (req, res, next) => {
  try {
    const token = req.header('Authorization')?.replace('Bearer ', '');
    
    if (!token) {
      return res.status(401).json({
        code: 401,
        message: '访问令牌缺失'
      });
    }

    const decoded = jwt.verify(token, config.jwt.adminSecret);
    const admin = await Admin.findByPk(decoded.adminId);
    
    if (!admin || !admin.is_active) {
      return res.status(401).json({
        code: 401,
        message: '管理员不存在或已被禁用'
      });
    }

    req.admin = admin;
    next();
  } catch (error) {
    if (error.name === 'JsonWebTokenError') {
      return res.status(401).json({
        code: 401,
        message: '无效的访问令牌'
      });
    }

    if (error.name === 'TokenExpiredError') {
      return res.status(401).json({
        code: 401,
        message: '访问令牌已过期'
      });
    }

    return res.status(500).json({
      code: 500,
      message: '认证失败'
    });
  }
};

// 超级管理员权限检查
export const requireSuperAdmin = (req, res, next) => {
  if (!req.admin || !req.admin.isSuperAdmin()) {
    return res.status(403).json({
      code: 403,
      message: '需要超级管理员权限'
    });
  }
  next();
};

// 可选的用户认证中间件（不强制要求登录）
export const optionalAuth = async (req, res, next) => {
  try {
    const token = req.header('Authorization')?.replace('Bearer ', '');

    if (token) {
      const decoded = jwt.verify(token, config.jwt.secret);
      const user = await User.findByPk(decoded.userId);

      if (user && user.is_active) {
        req.user = user;
      }
    }

    next();
  } catch (error) {
    // 可选认证失败时不返回错误，继续执行
    next();
  }
};

// 手机端用户认证中间件（专门用于小程序）
export const authenticateMobileUser = async (req, res, next) => {
  try {
    const token = req.header('Authorization')?.replace('Bearer ', '');

    if (!token) {
      return res.status(401).json({
        code: 401,
        message: '请先登录'
      });
    }

    const decoded = jwt.verify(token, config.jwt.secret);
    const user = await User.findByPk(decoded.userId);

    if (!user || !user.is_active) {
      return res.status(401).json({
        code: 401,
        message: '用户不存在或已被禁用'
      });
    }

    // 记录请求来源为手机端
    req.user = user;
    req.userAgent = req.get('User-Agent');
    req.clientType = 'mobile';
    next();
  } catch (error) {
    if (error.name === 'JsonWebTokenError') {
      return res.status(401).json({
        code: 401,
        message: '无效的访问令牌'
      });
    }

    if (error.name === 'TokenExpiredError') {
      return res.status(401).json({
        code: 401,
        message: '访问令牌已过期'
      });
    }

    return res.status(500).json({
      code: 500,
      message: '认证失败'
    });
  }
};

// 生成用户JWT令牌
export const generateUserToken = (user) => {
  return jwt.sign(
    { 
      userId: user.id,
      phone: user.phone,
      type: 'user'
    },
    config.jwt.secret,
    { expiresIn: config.jwt.expiresIn }
  );
};

// 生成管理员JWT令牌
export const generateAdminToken = (admin) => {
  return jwt.sign(
    { 
      adminId: admin.id,
      username: admin.username,
      role: admin.role,
      type: 'admin'
    },
    config.jwt.adminSecret,
    { expiresIn: config.jwt.expiresIn }
  );
};

// 验证令牌（不通过中间件）
export const verifyToken = (token, isAdmin = false) => {
  try {
    const secret = isAdmin ? config.jwt.adminSecret : config.jwt.secret;
    return jwt.verify(token, secret);
  } catch (error) {
    return null;
  }
};
